<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row :gutter="16" class="query-form2" v-show="!switchFlag">
        <Col span="8">
          <FormItem label="作品名称：" prop="worksTitle">
            <Input class="query-form-el" type="text" v-model="form1.worksTitle"></Input>
          </FormItem>
        </Col>
        <Col span="8">

          <FormItem label="作品类型：">
            <Select filterable v-model="form1.worksType">
              <Option v-for="item in woksTypeList" :value="item.value" :key="item.value">{{ item.name }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query1">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">
              展开
              <Icon type="ios-arrow-down"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="作品名称：" prop="worksTitle">
            <Input class="query-form-el" type="text" v-model="form1.worksTitle"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作品类型：">
            <Select filterable v-model="form1.worksType">
              <Option v-for="item in woksTypeList" :value="item.value" :key="item.value">{{ item.name }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="活动名称：">
            <Input class="query-form-el" type="text" v-model="form1.activityName"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="活动主题：" prop="themeName">
            <Input class="query-form-el" type="text" v-model="form1.themeName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作者：" prop="createUserName">
            <Input class="query-form-el" type="text" v-model="form1.createUserName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="所属单位：" prop="orgName">
            <Input class="query-form-el" type="text" v-model="form1.orgName"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="发布时间：">
            <Date-picker type="daterange" style="width: 95%" v-model="createDate"/>
          </FormItem>
        </Col>
        <Col span="8" offset="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query1">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2"
                    type="text">收起
              <Icon type="ios-arrow-up"/>
            </Button>
          </div>
        </Col>
      </Row>

    </Form>

    <Table ref='table' :height="tableHeight" :loading="loading" @on-selection-change='getSelectRows'
           border :columns="columns1" :data="dataTable" @on-sort-change="sortChange">
    </Table>

    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>



    <Modal title="作品审批" :transfer=false v-model="model1" :width=500>
      <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="审批结果：" prop="top">
              <Select v-model="form1datacopy.top" style="width:100%">
                <Option  value="3" >通过</Option>
                <Option  value="2" >不通过</Option>
              </Select>
            </FormItem>
          </Col>

        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg" v-if="form1datacopy.top == '3'">
          <Col span="11">
            <FormItem label="置顶等级：" prop="topLevel">
              <InputNumber :min="1" v-model="form1datacopy.topLevel" style="width:100%"></InputNumber>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="置顶到期时间：" prop="expireDate">
              <Date-picker :options="options" type="date" v-model="form1datacopy.expireDate" placeholder="选择日期"
                           style="width: 100%"></Date-picker>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button @click="submit('form1datacopy')" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
        <Button @click="handleCancel" class="ivu-btn-cancel">取消</Button>
      </div>
    </Modal>
    <Modal title="作品信息详情" :transfer=false v-model="model2" :width=1000 class="modal-view-detail">
      <Row>
        <Col span="24">
          <Form :model="showdata" :label-width="120">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="7">
                <FormItem label="作品名称：" prop="worksTitle">
                  {{showdata.worksTitle}}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="作品类型：" prop="worksName">
                  {{showdata.worksName}}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="活动内容：" prop="activityName">
                  {{showdata.activityName}}
                </FormItem>
              </Col>


            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="7">
                <FormItem label="活动主题：" prop="themeName">
                  {{showdata.themeName}}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="作者：" prop="createUserName">
                  {{showdata.createUserName}}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="发布时间：" prop="updateDate">
                  {{this.formatDate(new Date(showdata.updateDate), 'yyyy-MM-dd')}}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="7">
                <FormItem label="浏览量：" prop="browse">
                  {{showdata.browse}}
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="点赞量：" prop="thumbs">
                  {{showdata.thumbs}}
                </FormItem>
              </Col>
              <Col span="7">

              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="所属单位：" prop="orgName">
                  {{showdata.orgName}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="描述：" prop="tpshow">
                  <div v-html="showdata.tpshow">

                  </div>
                </FormItem>
              </Col>
            </Row>

            <Row v-if="showdata.worksType === '0'" type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="图片：" prop="imgs ">
                                    <span v-for="(file,index) in imgs" :key="index" style="margin-right: 10px">
                                        <div style="width: 25%;height: 25%;">
                                            <router-link target="_blank" :to="{path:'/imgDetails',query:{id:file.id}}">
                                                  <img :src="file.picture" alt="" style="width: 100%;height: 100%;">
                                            </router-link>

                                            <a @click.prevent="downloadFile(file.id,file.fileName)">{{file.fileName}}</a>
                                        </div>
                                    </span>
                </FormItem>
              </Col>
            </Row>
            <Row v-if="showdata.worksType === '1'" type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="视频：" prop="imgs ">
                                    <span v-for="(file,index) in imgs" :key="index" style="margin-right: 10px">
                                        <a @click.prevent="downloadFile(file.id,file.fileName)">{{file.fileName}}</a>
                                    </span>
                </FormItem>
              </Col>
            </Row>
            <Row v-if="showdata.worksType === '2'" type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <quill-editor ref="myTextEditor" v-model="showdata.worksContent"
                              style="height:300px;padding-top: 20px;padding-bottom: 60px"></quill-editor>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>
  </layout>
</template>

<script>
import {Api} from '../../../../api/index.js'
import {quillEditor} from 'vue-quill-editor'
import {sessionStorage} from '../../../../common/cacheUtils.js';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      currentUser:sessionStorage('userId').getObject('userId'),
      buttonLoading: false,
      loading: false,
      title: "",
      upUrl: Api.uploadMongoFileByKeyAndType,
      switchFlag: false,
      form1: {},
      //分页参数
      pageSizeArray: [10, 20, 50],
      imgs: [null, null],
      woksTypeList: [
        {
          name: "图片",
          value: "0",
        },
        {
          name: "视频",
          value: "1",
        },

      ],
      createDate: ["", ""],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      options: {
        disabledDate(date) {
          return date && date.valueOf() < new Date();
        }
      },
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '状态',
          align: 'center',
          key: 'status',
          fixed: 'left',
          width: 100,
          render: (h, params) => {
            let color = 'green';
            if (params.row.top == undefined || params.row.top == null || params.row.top == 2 || params.row.top == '0') {
              color = 'red';
            }
            if (params.row.top == 1) {
              color = 'blue';
            }
            return h('div', [
              h('span', {
                style: {
                  color: color
                }
              }, params.row.top == 1 ? '审批中' : params.row.top == 2 ? '审批驳回' : params.row.top == 3 ? '已置顶' : '未置顶' || '--')
            ]);
          }
        },
        {
          minWidth: 300,
          title: '作品名称',
          key: 'worksTitle',
          align: 'center'
        },
        {
          minWidth: 300,
          title: '作品类型',
          key: 'worksType',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              (params.row.worksType === '0' ? '图片' : params.row.worksType === '1' ? '视频' : '图文')
            ]);
          }

        },
        {
          minWidth: 300,
          title: '活动名称',
          key: 'activityName',
          align: 'center'
        },
        {
          minWidth: 300,
          title: '活动主题',
          align: 'center',
          key: 'themeName',
        },


        {
          minWidth: 280,
          title: '作者',
          key: 'createUserName',
          align: 'center'
        },
        {
          minWidth: 280,
          title: '所属单位',
          key: 'orgName',
          align: 'center',
          ellipsis: true
        },
        {
          minWidth: 200,
          title: '发布时间',
          key: 'updateDate',
          sortable: "custom",
          align: 'center',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.updateDate), 'yyyy-MM-dd'))
            ]);
          }

        },
        {
          minWidth: 200,
          title: '浏览量',
          key: 'browse',
          align: 'center'
        },
        {
          minWidth: 200,
          title: '点赞量',
          key: 'thumbs',
          align: 'center'
        },

        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 180,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.showData(params, 1);
                  }
                }
              }, '详情'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.showData(params, 2);
                  }
                }
              }, '审批'),
            ]);
          }
        }
      ],
      ruleCustom: {
        top: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        topLevel: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        expireDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      form1datacopy: {},
      dataTable: [],
      showdata: {},
      model1: false,
      model2: false,
      modelEdit: false,
      add: false,
      tableHeight: 10,
      file: null,
      fileName: null,
      downloadUrl: Api.downloadMongoFile,
      fileFj: '',
      themeList: [],
      activityList: [],
      fileType: 'jpg,jpeg,png',

    }
  },
  mounted: function () {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.query();
    this.selectThemeList();
    //this.selectActivityList();
  },
  methods: {
    top(params){
      let url = Api.topApprovalActivityWork;
      this.$http.get(url + '/' + params.row.id).then((res) => {
        console.log(res.data)
        if (res.data.status == 200){
          this.$Message.success('审批成功');
          this.query()
        }else{
          this.$Message.success('审批失败');
          this.query()
        }

      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 88;
      } else {
        this.tableHeight = this.tableHeight + 88;
      }
    },
    selectThemeList() {
      let data = {
        orgId: sessionStorage('userId').getObject('userId').companyId,
        activityType:this.$route.query.type
      }

      let url = Api.queryProgramme;
      this.$http.get(url, {params: data}).then((res) => {
        this.themeList = res.data.data.data;
        console.log(this.themeList)
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },

    selectActivityList(themeId) {
      let data = {
        orgId: sessionStorage('userId').getObject('userId').companyId,
        activityThemeId: themeId,
      }

      let url = Api.queryActivityMessage;
      this.$http.get(url, {params: data}).then((res) => {
        this.activityList = res.data.data.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },

    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },

    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },
    deleteImgs(id, type) {
      this.$http.delete(Api.uploadMongoFile + "/" + id).then((res) => {

        if (res.data.result == "success") {
          this.getFile(this.form1datacopy.id, type);

        }
      }).catch(e => {
        this.$Message.error("附件上传失败");
      });
    },
    sortChange(data) {
      if (data.order === 'asc' || data.order === 'desc') {
        let order = data.key
        this.form1.dynamicSort = order + ' ' + data.order
        this.query()
      }
    },
    beforeUploadImg(file) {
      var index = file.name.lastIndexOf(".");
      var suffix = file.name.substr(index + 1);

      if (suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png') {
        this.$Message.error("请上传jpg,jpeg,png格式的图片");
        this.file = null;
        this.fileName = null;
      } else {
        if (this.imgs.length <= 2) {
          const files = file;
          let formData = new FormData();
          formData.append("files", files);
          this.$http.post(Api.uploadMongoFileByKeyAndType + "/" + this.form1datacopy.id + "/files/picture", formData).then((res) => {
            if (res.data.result == "success") {
              this.getFile(this.form1datacopy.id, "picture");
            } else {
              this.$Message.error("附件上传失败");
            }
          }).catch(e => {
            this.$Message.error("附件上传失败");
          });

        } else {
          this.$Message.error("最多允许上传3张图片");
        }

      }
      return false;
    },
    getFile(id, type) {
      this.$http.get(Api.interestedPartiesUserFile + "/" + id + "/files/" + type).then((res) => {
        if (res.data.result == "success") {
          this.imgs = res.data.data;
        }
      }).catch(e => {
        this.$Message.error("文件读取失败");
      });

    },
    beforeUploadVideo(file) {
      var index = file.name.lastIndexOf(".");
      var suffix = file.name.substr(index + 1);
      if ((suffix != 'mp4' && suffix != 'avi' && suffix != 'rm') || file.size > 1024 * 1024 * 50) {
        this.$Message.error("请上传mp4,avi,rm格式的，小于50MB的视频");
        this.file = null;
        this.fileName = null;
      } else {
        if (this.imgs.length < 1) {
          const files = file;
          let formData = new FormData();
          formData.append("files", files);
          this.$http.post(Api.uploadMongoFileByKeyAndType + "/" + this.form1datacopy.id + "/files/video", formData).then((res) => {
            if (res.data.result == "success") {
              this.getFile(this.form1datacopy.id, "video");

            } else {
              this.$Message.error("附件上传失败");
            }
          }).catch(e => {
            this.$Message.error("附件上传失败");
          });
        } else {
          this.$Message.error("请先删除视频在上传");
        }


      }
      return false;
    },

    showData(data, flag) {
      this.buttonLoading = false;
      if (flag == 1) {
        //查看页面

        this.$http.get(Api.getActivityWork + "/" + data.row.id).then((res) => {

          this.showdata = res.data.data[0];
          if (data.row.worksType === '1') {
            this.showdata.worksName = "视频";
            this.getFile(data.row.id, 'video')
          } else if (data.row.worksType === '0') {
            this.showdata.worksName = "图片";
            this.getFile(data.row.id, 'picture')
          } else {
            this.showdata.worksName = "图文";
          }
        }).catch(e => {
          this.$Message.error("文件读取失败");
        });
        this.model2 = true;
      } else {
        //修改页面
        this.model1 = true;
        this.form1datacopy = {};
        this.form1datacopy.id = data.row.id;
        let dateTime = new Date();
        dateTime = dateTime.setDate(dateTime.getDate() + 30);
        dateTime = new Date(dateTime);
        this.form1datacopy.expireDate = dateTime
        this.form1datacopy.topLevel = 1;
      }


    },

    getSelectRows(rows) {
      this.deleteRows = rows;
    },

    deleteData(params) {
      let url = Api.deleteActivityWork;
      this.$http.delete(url + '/' + params.row.id).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })

    },

    query() {
      this.loading = true;

      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        activityType:this.$route.query.type
      }
      if (this.createDate[0] != "" && this.createDate[1] != "") {
        this.form1.startDate = this.formatDate(new Date(this.createDate[0]), 'yyyy-MM-dd');
        this.form1.endDate = this.formatDate(new Date(this.createDate[1]), 'yyyy-MM-dd');
      }


      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

      let url = Api.topListActivityWork;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data.data;
        this.loading = false;
        this.pagedata.total = res.data.data.totalSize;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    reset() {
      this.form1 = {};
      this.createDate = ["", ""];
      this.query1();
    },
    query1(){
      this.pagedata.currentPage = 1;
      this.query();
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
      this.modelEdit = false;
      this.file = null;
      this.fileName = null;
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
            if (this.form1datacopy.top != 3){
              this.form1datacopy.topLevel = null;
              this.form1datacopy.expireDate = null;
            }
            this.$http.post(Api.topActivityWork, this.form1datacopy).then((res) => {
              this.$Message.success("保存成功")
              this.buttonLoading = false;
              this.model1 = false;
              this.query();

            }).catch(e => {
              this.$Message.error({
                content: '保存失败',
                duration: 4
              });
            })
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    downloadFile(fileId, fileName) {
      let url = this.downloadUrl + "/" + fileId
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        console.log(res)
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.body.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    addInfo() {
      this.title = "作品信息新增";
      this.imgs = [];
      this.form1datacopy = {
        id: this.uuid(),
        top:'0',
      };
      this.add = true;
      this.model1 = true;

    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
      let uuid = s.join("");
      return uuid
    }
  },
}
</script>
<style lang='css' scoped>
@import '../../../../index.css';

</style>
